package gns

import (
	"fmt"
	"os/exec"
	"runtime"

	"gitee.com/liumou_site/gbm"
	"gitee.com/liumou_site/logger"
	"github.com/spf13/cast"
)

type PingCmd struct {
	host       string
	pingCount  int
	timeout    int
	Realtime   bool
	ExitStatus bool
}

// shellSystem 执行系统命令来执行 ping 操作，并返回命令的退出码、输出结果和可能的错误。
func (p *PingCmd) shellSystem() (code int, out string, err error) {
	var arg []string
	commandPath := "ping"
	if runtime.GOOS == "windows" {
		arg = append([]string{"-w", cast.ToString(p.timeout)}, p.host)
	} else {
		arg = append([]string{"-c", cast.ToString(p.pingCount), "-W", cast.ToString(p.timeout)}, p.host)
	}
	cmdline := commandPath + gbm.SliceToString(arg, " ")
	cmd := exec.Command(commandPath, arg...)
	stdout, err := cmd.StdoutPipe()
	cmd.Stderr = cmd.Stdout
	if err != nil {
		logger.Error("管道创建失败")
		logger.Debug("Execute command: ", cmdline)
		return 1, "管道创建失败", err
	}
	runErr := cmd.Start()
	if runErr != nil {
		logger.Error("命令启动失败 :", runErr)
		logger.Debug("Execute command: ", cmdline)
		return 2, "命令启动失败", runErr
	}
	var result string
	for {
		tmp := make([]byte, 1024)
		_, err := stdout.Read(tmp)
		if p.Realtime {
			fmt.Print(string(tmp))
		}
		result = result + cast.ToString(string(tmp))
		if err != nil {
			break
		}
	}
	waitErr := cmd.Wait()
	exitCode := cmd.ProcessState.ExitCode()
	if p.ExitStatus {
		logger.Info("Exit Code: ", exitCode)
	}
	if waitErr == nil {
		if exitCode != 0 {
			logger.Error("Error :", waitErr)
			logger.Debug("Execute command: ", cmdline)
			return exitCode, result, runErr
		}
		if exitCode == 0 {
			return exitCode, result, nil
		}
	}
	return exitCode, result, waitErr
}
